//
//  BVPayManager.m
//  BuyVegetables1
//
//  Created by pinkfloyd on 16/2/29.
//  Copyright © 2016年 叶思超. All rights reserved.
//

#import "BVPayManager.h"

@interface BVPayManager ()
@property (nonatomic,copy) successBlock successBlock;
@property (nonatomic,copy) faileBlock faileBlock;
@property (nonatomic,copy) finishBlock finishBlock;
@end
@implementation BVPayManager
+ (instancetype)manager{
    
    static BVPayManager * manager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        if (manager == nil) {
            manager = [[self alloc]init];
            [[NSNotificationCenter defaultCenter] addObserver:manager selector:@selector(getWXPayResult:) name:@"WXPayResultNotification" object:nil];
        }
    });
    return manager;
}
- (void)pay:(PayType)payType
   orderNum:(NSString *)orderNum
finishBlock:(finishBlock)finishBlock
successBlock:(successBlock)successBlock
 faileBlock:(faileBlock)faileBlock{
    
    
    self.finishBlock  = finishBlock;
    self.successBlock = successBlock;
    self.faileBlock   = faileBlock;
    if (payType == PayTypeAliPay) {
        [self aliPay:orderNum];
    }else if(payType == PayTypeWX){
        [self wxPay:orderNum];
    }
}
/**
 微信支付
 */
- (void)wxPay:(NSString *)ordrNum
{
    
    NSString *urlString   = @"http://app.jingcaibuy.com/VegetablePayAPI/weixin";
    AFHTTPSessionManager * manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    NSDictionary * params = @{@"orderid":ordrNum};
    [manager POST:urlString parameters:params success:^(NSURLSessionDataTask *task, id responseObject) {
        
        NSError * error = nil;
        NSMutableDictionary * baseDict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:&error];
        if (error || responseObject == nil) {
            if (self.faileBlock) {
                self.finishBlock();
            }
            return ;
        }
        NSMutableString *retcode = [baseDict objectForKey:@"code"];
        if ([retcode isEqualToString:@"1"]){
            
            NSDictionary * dataDict = baseDict[@"data"];
            NSMutableString *stamp  = [dataDict objectForKey:@"timestamp"];
            PayReq* req = [[PayReq alloc] init];
            req.partnerId = [dataDict objectForKey:@"partnerid"];
            req.prepayId = [dataDict objectForKey:@"prepayid"];
            req.nonceStr = [dataDict objectForKey:@"noncestr"];
            req.timeStamp = stamp.intValue;
            req.package = [dataDict objectForKey:@"package"];
            req.sign = [dataDict objectForKey:@"sign"];
            [WXApi sendReq:req];
        }
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        if (self.faileBlock) {
            self.faileBlock();
        }
    }];
}
/**
 支付宝支付
 */
- (void)aliPay:(NSString *)orderNum
{
     
    AFHTTPSessionManager * manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    NSDictionary * dict = @{@"orderid":orderNum};
    [manager POST:@"http://app.jingcaibuy.com/VegetablePayAPI/zmoney" parameters:dict success:^(NSURLSessionDataTask *task, id responseObject) {
        
        NSDictionary * baseDict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        
        if ([baseDict[@"code"] isEqualToString:@"0"]) {
            if (self.faileBlock) {
                self.faileBlock();
                return ;
            }
        }
        
        Order *order = [[Order alloc] init];
        order.partner = Partner;
        order.seller = Seller;
        order.tradeNO = orderNum; //订单ID（由商家自行制定）
        order.productName = @"精菜"; //商品标题
        order.productDescription = @"走过路过不要错过"; //商品描述
        order.notifyURL = NotifyURL; //回调URL
        order.service = Service;//支付宝支付服务器名称
        order.paymentType = PaymentType;
        order.inputCharset = InputCharset;
        order.itBPay = ItBPay;
        order.showUrl = ShowUrl;
        order.amount = baseDict[@"data"][@"money"];
        NSString *orderSpec = [order description];
        
        //创建RSA加密的秘钥
        id<DataSigner> signer = CreateRSADataSigner(AliPrivateKey);
        //签名
        NSString *signerStr = [signer signString:orderSpec];
        NSString *orderStr = nil;
        if (signerStr) {
            orderStr = [NSString stringWithFormat:@"%@&sign=\"%@\"&sign_type=\"%@\"",
                        orderSpec, signerStr, @"RSA"];
        [[AlipaySDK defaultService] payOrder:orderStr fromScheme:@"HaoMaiSong" callback:^(NSDictionary *resultDic) {
            
            if (self.finishBlock) {
                self.finishBlock();
            }
            
            if ([resultDic[@"resultStatus"] isEqualToString:@"9000"]) {
                
                if (self.successBlock) {
                    self.successBlock();
                }
            }
            else{
                if (self.faileBlock) {
                    self.faileBlock();
                }
            }
        }];

        }
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        if (self.faileBlock) {
            self.faileBlock();
        }
    }];
}
/**
 微信支付回调
 */
- (void)getWXPayResult:(NSNotification *)notify{
    
    if (self.finishBlock) self.finishBlock();
    BaseResp * resp = notify.userInfo[@"PayResult"];
    switch (resp.errCode) {
        case WXSuccess:
            if (self.successBlock) self.successBlock();
            //正规做法是  WXSuccess之后再去查询服务器，才能确定支付结果是否成功
            break;
            
        default:
            if (self.faileBlock) self.faileBlock();
            break;
    }
    
}

- (void)dealloc{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}
@end
